package com.zjw.service.impl;


import com.zjw.constants.SystemConstants;
import com.zjw.annotation.domain.entity.Menu;
import com.zjw.annotation.domain.entity.Role;
import com.zjw.annotation.domain.entity.User;
import com.zjw.mapper.UserMapper;
import com.zjw.service.MenuService;
import com.zjw.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

//        更具用户名查询用户实体
        User targetUser = userMapper.getByName(username);
        if (targetUser == null)
            throw new UsernameNotFoundException("用户不存在！");

//        返回UserDetails类型的user对象
//        org.springframework.security.core.userdetails.User user =
//                new org.springframework.security.core.userdetails.User(
//                        targetUser.getUserName(),
//                        targetUser.getPassword(),
////                        暂时不查询用户的权限信息
//                        AuthorityUtils.NO_AUTHORITIES
//                );
        if (targetUser.getType().equals(SystemConstants.USER_TYPE_ADMIN)) {
//            后台管理员才进行权限和角色的封装
            List<Role> roles = roleService.getRolesById(targetUser.getId());
            List<Menu> menus = menuService.getPermsById(targetUser.getId());
            List<String> authorities = new ArrayList<>();


            roles.stream().forEach(r -> {
                authorities.add(SystemConstants.AUTHORITIES_ROLE_PREFIX + r.getRoleKey());
            });
            menus.stream().forEach(m -> {
                authorities.add(m.getPerms());
            });
            LoginUser user = new LoginUser(targetUser, authorities);
            return user;
        }
        //        使用自定义的实现类
        LoginUser user = new LoginUser(targetUser, null);
        return user;
    }
}
